package com.stop.think.shiro.service.paypal;

import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class PayPalService {

  public HttpResponse<Order> captureOrder(String orderId) throws IOException {
    OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
    request.requestBody(buildRequestBody());
    //3. Call PayPal to capture an order
    HttpResponse<Order> response = PayPalClient.client().execute(request);
    //4. Save the capture ID to your database. Implement logic to save capture to your database for future reference.
    System.out.println("Status Code: " + response.statusCode());
    System.out.println("Status: " + response.result().status());
    System.out.println("Order ID: " + response.result().id());
    System.out.println("Links: ");
    for (LinkDescription link : response.result().links()) {
      System.out.println("\t" + link.rel() + ": " + link.href());
    }
    System.out.println("Capture ids:");
    for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
      for (Capture capture : purchaseUnit.payments().captures()) {
        System.out.println("\t" + capture.id());
      }
    }
    System.out.println("Buyer: ");
    Payer buyer = response.result().payer();
    System.out.println("\tEmail Address: " + buyer.email());
    System.out.println("\tName: " + buyer.name().fullName());
    return response;
  }

  /**
   *Creating empty body for capture request.
   *You can set the payment source if required.
   *
   *@return OrderRequest request with empty body
   */
  public OrderRequest buildRequestBody() {
    return new OrderRequest();
  }
}
